import React, { useState, useEffect, useRef } from "react";
import { Card, Button, Table, Modal, message } from "antd";
import { reqUsers, reqAddOrUpdateUser, reqRemoveUser } from "../../api";
import UserForm from "./user-form";

const User = () => {
  const [users, setUsers] = useState([]);
  const [roles, setRoles] = useState([]);
  const [open, setOpen] = useState(false);
  const [currentUser, setCurrentUser] = useState(null);
  const formRef = useRef();

  useEffect(() => {
    getUsers();
  }, []);

  const columns = [
    {
      title: "用户名",
      dataIndex: "username",
    },
    {
      title: "邮箱",
      dataIndex: "email",
    },
    {
      title: "电话",
      dataIndex: "phone",
    },
    {
      title: "注册时间",
      dataIndex: "create_time",
      render: (create_time) =>
        create_time ? new Date(create_time).toLocaleString() : "",
    },
    {
      title: "所属角色",
      dataIndex: "role_id",
      render: (role_id) => roles.find((role) => role._id === role_id)?.name,
    },
    {
      title: "操作",
      render: (user) => (
        <span>
          <Button
            type="primary"
            onClick={() => updateUser(user)}
            style={{ marginRight: 10 }}
          >
            修改
          </Button>
          <Button type="default" onClick={() => removeUser(user)}>
            删除
          </Button>
        </span>
      ),
    },
  ];

  const removeUser = (user) => {
    Modal.confirm({
      title: `确定删除${user.username}用户吗？`,
      okText: "确定",
      okType: "danger",
      cancelText: "取消",
      onOk: async () => {
        const res = await reqRemoveUser(user._id);
        if (res.status === 0) {
          message.success("删除用户成功");
          getUsers();
        } else {
          message.error(res.msg);
        }
      },
    });
  };

  const updateUser = (user) => {
    setCurrentUser(user);
    setOpen(true);
  };

  const getUsers = async () => {
    const res = await reqUsers();
    if (res.status === 0) {
      const { users, roles } = res.data;
      setUsers(users);
      setRoles(roles);
    }
  };

  const showAddUser = () => {
    setCurrentUser(null);
    setOpen(true);
  };

  const handleOk = async () => {
    try {
      const values = await formRef.current.validateFields();
      if (currentUser) {
        values._id = currentUser._id;
      }
      const res = await reqAddOrUpdateUser(values);
      if (res.status === 0) {
        message.success("添加/更新用户成功");
        getUsers();
      } else {
        message.error(res.msg);
      }
      setOpen(false);
    } catch (err) {
      console.log(err);
    }
  };

  const handleCancel = () => {
    setOpen(false);
  };

  return (
    <Card
      title={
        <Button type="primary" onClick={showAddUser}>
          创建用户
        </Button>
      }
    >
      <Table
        bordered
        rowKey="_id"
        columns={columns}
        dataSource={users}
        pagination={{ defaultPageSize: 2 }}
      />
      <Modal
        title={currentUser ? "修改用户" : "添加用户"}
        open={open}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
      >
        <UserForm ref={formRef} roles={roles} user={currentUser || {}} />
      </Modal>
    </Card>
  );
};

export default User;
